package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.InventoryDistribution;
import com.geek.factory.entity.WarehouseShelves;
import com.geek.factory.entity.Shelves;
import com.geek.factory.entity.Warehouse;
import com.geek.factory.result.Result;
import com.geek.factory.service.IInventoryDistributionService;
import com.geek.factory.service.IWarehouseShelvesService;
import com.geek.factory.service.IShelvesService;
import com.geek.factory.service.IWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仓库货柜关联管理控制器
 */
@RestController
@RequestMapping("/warehouse-shelf")
@Api(tags = "后台系统的 - 仓库货柜关联模块")
@Slf4j
@CrossOrigin
public class WarehouseShelvesController {

    @Autowired
    private IWarehouseShelvesService warehouseShelvesService;

    @Autowired
    private IShelvesService shelvesService;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IInventoryDistributionService inventoryDistributionService;

    @ApiOperation("通过ID查询关联信息")
    @GetMapping("/{relationId}")
    public Result findWarehouseShelvesById(@ApiParam("关联ID") @PathVariable("relationId") Integer relationId) {
        WarehouseShelves warehouseShelves = warehouseShelvesService.getById(relationId);
        log.info("warehouseShelves: {}", warehouseShelves);
        if (warehouseShelves != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", warehouseShelves);
        }
        return new Result(SuccessConstant.FAIL, "关联记录不存在");
    }

    // 新增仓库货柜关联
    @ApiOperation("新增仓库货柜关联")
    @PostMapping
    public Result addWarehouseShelves(@RequestBody WarehouseShelves warehouseShelves) {
        warehouseShelves.setCreatedTime(LocalDateTime.now());
        warehouseShelves.setCreatedBy("admin"); // 实际项目中应从登录用户获取
        boolean isSuccess = warehouseShelvesService.save(warehouseShelves);
        log.info("新增关联: {}, 结果: {}", warehouseShelves, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", warehouseShelves);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    // 根据ID删除关联
    @ApiOperation("根据ID删除关联")
    @DeleteMapping("/{relationId}")
    public Result deleteWarehouseShelves(@ApiParam("关联ID") @PathVariable("relationId") Integer relationId) {
        boolean isSuccess = warehouseShelvesService.removeById(relationId);
        log.info("删除关联ID: {}, 结果: {}", relationId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    // 修改关联信息
    @ApiOperation("修改关联信息")
    @PutMapping("/{relationId}")
    public Result updateWarehouseShelves(@ApiParam("关联ID") @PathVariable("relationId") Integer relationId, @RequestBody WarehouseShelves warehouseShelves) {
        warehouseShelves.setRelationId(relationId);
        boolean isSuccess = warehouseShelvesService.updateById(warehouseShelves);
        log.info("修改关联: {}, 结果: {}", warehouseShelves, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", warehouseShelves);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("分页查询关联列表（包含货柜和仓库详细信息）")
    @GetMapping("/page")
    public Result getWarehouseShelvesPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer warehouseId,
            @RequestParam(required = false) Integer shelfId,
            @RequestParam(required = false) String areaCode,
            @RequestParam(required = false) Boolean status
    ) {
        LambdaQueryWrapper<WarehouseShelves> wrapper = new LambdaQueryWrapper<>();
        if (warehouseId != null) {
            wrapper.eq(WarehouseShelves::getWarehouseId, warehouseId);
        }
        if (shelfId != null) {
            wrapper.eq(WarehouseShelves::getShelfId, shelfId);
        }
        if (areaCode != null && !areaCode.trim().isEmpty()) {
            wrapper.like(WarehouseShelves::getAreaCode, areaCode);
        }
        if (status != null) {
            wrapper.eq(WarehouseShelves::getStatus, status);
        }
        wrapper.orderByDesc(WarehouseShelves::getCreatedTime);

        Page<WarehouseShelves> page = warehouseShelvesService.page(new Page<>(current, size), wrapper);

        // 获取关联的货柜和仓库详细信息
        List<WarehouseShelves> records = page.getRecords();
        List<Map<String, Object>> enrichedRecords = records.stream().map(record -> {
            Map<String, Object> enrichedRecord = new HashMap<>();

            // 复制关联表的基本信息
            enrichedRecord.put("relationId", record.getRelationId());
            enrichedRecord.put("warehouseId", record.getWarehouseId());
            enrichedRecord.put("shelfId", record.getShelfId());
            enrichedRecord.put("areaCode", record.getAreaCode());
            enrichedRecord.put("positionX", record.getPositionX());
            enrichedRecord.put("positionY", record.getPositionY());
            enrichedRecord.put("positionZ", record.getPositionZ());
            enrichedRecord.put("status", record.getStatus());
            enrichedRecord.put("remarks", record.getRemarks());
            enrichedRecord.put("createdBy", record.getCreatedBy());
            enrichedRecord.put("createdTime", record.getCreatedTime());

            // 获取货柜详细信息
            Shelves shelves = shelvesService.getById(record.getShelfId());
            if (shelves != null) {
                enrichedRecord.put("shelfName", shelves.getShelfName());
                enrichedRecord.put("shelfCode", shelves.getShelfCode());
                enrichedRecord.put("capacity", shelves.getCapacity());
                enrichedRecord.put("capacityUnit", shelves.getCapacityUnit());
                enrichedRecord.put("locationCode", shelves.getLocationCode());
            }

            // 获取仓库详细信息
            Warehouse warehouse = warehouseService.getById(record.getWarehouseId());
            if (warehouse != null) {
                enrichedRecord.put("warehouseName", warehouse.getWarehouseName());
                enrichedRecord.put("warehouseCode", warehouse.getWarehouseCode());
            }

            return enrichedRecord;
        }).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();
        data.put("records", enrichedRecords);
        data.put("total", page.getTotal());
        data.put("current", page.getCurrent());
        data.put("size", page.getSize());
        data.put("pages", page.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("根据仓库ID获取关联的货柜列表（包含详细信息）")
    @GetMapping("/warehouse/{warehouseId}")
    public Result getShelvesByWarehouseId(@PathVariable Integer warehouseId) {
        LambdaQueryWrapper<WarehouseShelves> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WarehouseShelves::getWarehouseId, warehouseId);
        wrapper.eq(WarehouseShelves::getStatus, true); // 只查询启用的关联
        List<WarehouseShelves> warehouseShelves = warehouseShelvesService.list(wrapper);

        // 获取关联的货柜详细信息
        List<Map<String, Object>> enrichedRecords = warehouseShelves.stream().map(record -> {
            Map<String, Object> enrichedRecord = new HashMap<>();

            // 复制关联表的基本信息
            enrichedRecord.put("relationId", record.getRelationId());
            enrichedRecord.put("warehouseId", record.getWarehouseId());
            enrichedRecord.put("shelfId", record.getShelfId());
            enrichedRecord.put("areaCode", record.getAreaCode());
            enrichedRecord.put("positionX", record.getPositionX());
            enrichedRecord.put("positionY", record.getPositionY());
            enrichedRecord.put("positionZ", record.getPositionZ());
            enrichedRecord.put("status", record.getStatus());
            enrichedRecord.put("remarks", record.getRemarks());
            enrichedRecord.put("createdBy", record.getCreatedBy());
            enrichedRecord.put("createdTime", record.getCreatedTime());

            // 获取货柜详细信息
            Shelves shelves = shelvesService.getById(record.getShelfId());
            if (shelves != null) {
                enrichedRecord.put("shelfName", shelves.getShelfName());
                enrichedRecord.put("shelfCode", shelves.getShelfCode());
                enrichedRecord.put("capacity", shelves.getCapacity());
                enrichedRecord.put("capacityUnit", shelves.getCapacityUnit());
                enrichedRecord.put("locationCode", shelves.getLocationCode());
            }

            return enrichedRecord;
        }).collect(Collectors.toList());

        return new Result(SuccessConstant.SUCCESS, "查询成功", enrichedRecords);
    }

    @ApiOperation("根据货柜ID获取关联的仓库列表")
    @GetMapping("/shelf/{shelfId}")
    public Result getWarehousesByShelfId(@PathVariable Integer shelfId) {
        LambdaQueryWrapper<WarehouseShelves> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WarehouseShelves::getShelfId, shelfId);
        wrapper.eq(WarehouseShelves::getStatus, true); // 只查询启用的关联
        List<WarehouseShelves> warehouseShelves = warehouseShelvesService.list(wrapper);
        return new Result(SuccessConstant.SUCCESS, "查询成功", warehouseShelves);
    }
    @ApiOperation("统计某产品或原料在各仓库的分布")
    @GetMapping("/statistics")
    public Result getInventoryStatistics(
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) Integer materialId
    ) {
        if (productId == null && materialId == null) {
            return new Result(SuccessConstant.FAIL, "必须指定产品ID或原料ID");
        }

        QueryWrapper<InventoryDistribution> wrapper = new QueryWrapper<>();
        if (productId != null) {
            wrapper.eq("product_id", productId);
        }
        if (materialId != null) {
            wrapper.eq("material_id", materialId);
        }

        // 查询所有相关分布
        List<InventoryDistribution> list = inventoryDistributionService.list(wrapper);

        // 按仓库分组统计数量
        Map<Integer, BigDecimal> warehouseQuantityMap = new HashMap<>();
        for (InventoryDistribution dist : list) {
            Integer warehouseId = dist.getWarehouseId();
            BigDecimal quantity = dist.getQuantity();
            warehouseQuantityMap.put(warehouseId,
                    warehouseQuantityMap.getOrDefault(warehouseId, BigDecimal.ZERO).add(quantity));
        }

        // 查询仓库名称
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<Integer, BigDecimal> entry : warehouseQuantityMap.entrySet()) {
            Integer warehouseId = entry.getKey();
            BigDecimal quantity = entry.getValue();
            // 你可以通过仓库Service查名称
            String warehouseName = "未知";
            Warehouse warehouse = warehouseService.getById(warehouseId);
            if (warehouse != null) {
                warehouseName = warehouse.getWarehouseName();
            }
            Map<String, Object> item = new HashMap<>();
            item.put("warehouseId", warehouseId);
            item.put("warehouseName", warehouseName);
            item.put("quantity", quantity);
            result.add(item);
        }

        return new Result(SuccessConstant.SUCCESS, "统计成功", result);
    }
}